import { BadRequestException, Inject, Injectable } from '@nestjs/common';
import { CreateRoomDto } from 'src/dto/CreateRoom.dto';
import { updateRoomDto } from 'src/dto/UpdateRoom.dto';
import { PaginationService } from 'src/hooks/usePagination';
import { PrismaService } from 'src/prisma/prisma.service';

@Injectable()
export class RoomService {
  @Inject(PrismaService)
  private readonly prisma: PrismaService;

  @Inject(PaginationService)
  private readonly paginationService: PaginationService;

  async isRoomExist(id: number) {
    const room = await this.prisma.room.findUnique({
      where: {
        id,
      },
    });
    if (!room) throw new BadRequestException('会议室不存在');
    return room;
  }

  async getRoomList(
    num: number,
    size: number,
    name: string,
    capacity: number,
    equipment: string,
  ) {
    const query = {
      where: {
        name: {
          contains: name,
        },
        capacity: {
          gte: +capacity,
        },
        equipment: {
          contains: equipment,
        },
      },
    };

    return await this.paginationService.paginate('room', query, num, size);
  }

  async createRoom(room: CreateRoomDto) {
    const roomExit = await this.prisma.room.findUnique({
      where: {
        name: room.name,
      },
    });

    if (roomExit) throw new BadRequestException('会议室已存在');
    await this.prisma.room.create({
      data: {
        ...room,
      },
      select: {
        id: true,
      },
    });
  }

  async updateRoom(room: updateRoomDto) {
    await this.isRoomExist(room.id);

    const roomList = await this.prisma.room.findMany({
      where: {
        id: {
          not: room.id,
        },
        name: room.name,
      },
    });

    if (roomList.length) throw new BadRequestException('会议室名称不能重复');

    await this.prisma.room.update({
      where: {
        id: room.id,
      },
      data: {
        ...room,
      },
    });
  }

  async getRoomInfoById(id: number) {
    return await this.isRoomExist(id);
  }

  async deleteRoom(id: number) {
    await this.isRoomExist(id);

    await this.prisma.room.delete({
      where: {
        id,
      },
    });
  }
}
